package com.mall.user.services;


import com.alibaba.fastjson.JSON;


import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;


import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service


@Slf4j
@Component
public class RegisterServiceImpl implements IRegisterService {


    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired

    private JavaMailSender mailSender;


    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();
        // 校验用户名密码不能为空
        request.requestCheck();
        // 判断用户名是否重复
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {
            response.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
            response.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return response;
        }

        // 向member表中插入数据
        Member member = new Member();
        member.setUsername(request.getUserName());
        String userPwd = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        member.setPassword(userPwd);
        member.setEmail(request.getEmail());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N"); // 可以省略不写 数据库默认就是“N”
        // TODO: 这一步出现问题
        int effectRows = 0;
        try {
            effectRows = memberMapper.insert(member);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (effectRows != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }



        // 向用户验证表插入一条数据
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(request.getUserName());
        // 自己设置一个唯一的uuid
        StringBuilder stringBuilder = new StringBuilder();
        String uuid = stringBuilder.append(member.getUsername()).append(member.getPassword()).append(UUID.randomUUID().toString()).toString();
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        int effect = userVerifyMapper.insert(userVerify);
        if (effect != 1) {

            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }

        //3.发送用户激活邮件
        /*//打印日志
        log.info("用户注册成功，注册参数request:{},{}", JSON.toJSONString(registerRequest),"xxx");
        //用户注册成功，注册参数request:registerRequest,xxx*/
        //发送用户激活邮件 激活邮件应该时一个链接 有一个接口去处理我们的用户激活 消息中间件MQ




        // 发送激活邮件---邮件内容是一条链接
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                sendActiveMsg(uuid, request);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        // 打印日志
        log.info("用户注册成功: {}", request.getUserName());
        // 用户注册成功，返回结果

        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }


    //发送用户激活邮件
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();//新建一个待发送邮件的对象
        message.setSubject("CSMALL用户激活");
        message.setFrom("1801012289@qq.com");
        message.setTo(registerRequest.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8080/user/verify?uid=").append(uuid).
                append("&username").append(registerRequest.getUserName());
        //http://localhost:8080/user/verify?uid=xxxx&username=xxx
        message.setText(stringBuilder.toString());
        mailSender.send(message);
    }




    private void validUsernameRepetion(UserRegisterRequest request) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)) {

            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }



    /**
     * 发送激活邮件
     * @param uuid
     * @param request
     */
    private void sendActiveMsg(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("csmall商城用户注册激活");
        StringBuilder builder = new StringBuilder();
        String verifyUrl = builder.append("http://localhost:8080/user/verify?uid=").append(uuid).append("&username=").append(request.getUserName()).toString();
        message.setText(verifyUrl);
        message.setFrom("lzs329324712@163.com");
        message.setTo(request.getEmail());
        mailSender.send(message);
    }

}
